package qingyu.ai.ui.safe.bind;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.stepstone.stepper.StepperLayout;
import com.stepstone.stepper.VerificationError;
import com.vondear.rxtools.view.RxToast;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import qingyu.ai.GlobalApp;
import qingyu.ai.R;
import qingyu.ai.base.BaseBlockingStep;
import qingyu.ai.base.BaseEditTextListener;
import qingyu.ai.common.Constants;
import qingyu.ai.common.net.APIFactory;
import qingyu.ai.common.net.NetRequestAdapter;
import qingyu.ai.common.net.NetworkRequestCalback;
import qingyu.ai.common.net.RetrofitHttpUtil;
import qingyu.ai.common.util.EncryptUtil;
import qingyu.ai.common.util.SPUtil;
import qingyu.ai.domain.UserInfoData;
import qingyu.ai.ui.personal.PersonalActivity;
import qingyu.ai.ui.safe.OnProceedListener;

/**
 * 注册页面1
 */
public class BindAccountFragmentThree extends BaseBlockingStep implements NetworkRequestCalback<UserInfoData> {
    @BindView(R.id.password_register)
    TextInputLayout passwordRegister;
    private OnProceedListener proceedListener;

    @BindView(R.id.btn_done)
    Button btn_done;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.bindaccount_fragment_three, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    /**
     * 验证
     *
     * @return
     */
    @Nullable
    @Override
    public VerificationError verifyStep() {
        if (passwordRegister.getEditText().getText().length() < 8) {
            return new VerificationError("密码为大于8位的数字和字母");
        }
        return null;
    }

    /**
     * 设置提示信息
     *
     * @param error
     */
    @Override
    public void onError(@NonNull VerificationError error) {
        passwordRegister.setError("密码为大于8位的数字和字母");

    }

    /**
     * 完成注册
     *
     * @param callback
     */
    public void onCompleteClicked(StepperLayout.OnCompleteClickedCallback callback) {
        HashMap<String, String> map = new HashMap<>();
        String token = SPUtil.getString(Constants.userinfo.access_token, "");
        String passText = passwordRegister.getEditText().getText().toString();
        String passwordEncrypt = EncryptUtil.encryptMD5ToString(passText).toLowerCase();
        map.put("account", GlobalApp.account);
        map.put("token", token);
        map.put("code", GlobalApp.code);
        map.put("password", passwordEncrypt);
        new APIFactory(getContext(), RetrofitHttpUtil.BASE_URL).bindAccount(map, new NetRequestAdapter<UserInfoData>(this));
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnProceedListener)
            this.proceedListener = (OnProceedListener) context;
        else
            throw new IllegalStateException("Activity must implement OnProceedListener");
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        btn_done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //刷新Stepper的回调对应方法
                proceedListener.onProceed();
            }
        });
        passwordRegister.getEditText().addTextChangedListener(new BaseEditTextListener() {
            @Override
            public void afterTextChanged(Editable s) {
                passwordRegister.setError(null);
            }
        });
    }

    /**
     * 注册成功，默认已登陆，拿到token即已登陆
     * <p>
     * 保存 account、iconUrl、access_token和refresh_token
     * <p>
     * 重新登陆refresh_token会失效，不然永久不失效
     *
     * @param data
     */
    @Override
    public void onSuccess(UserInfoData data) {
        RxToast.success("绑定成功");
        SPUtil.putString(Constants.userinfo.account, GlobalApp.account);
        startActivity(new Intent(getActivity(), PersonalActivity.class));
        getActivity().finish();
    }

    /**
     * 注册失败，跳回登陆页面，重新选择登陆方式
     *
     * @param errorCode
     * @param erorMsg
     */
    @Override
    public void onError(int errorCode, String erorMsg) {
        Log.e("xixi", errorCode + "---" + erorMsg);
        startActivity(new Intent(getActivity(), PersonalActivity.class));
        getActivity().finish();
        RxToast.error("绑定失败，请重新绑定！");
    }

    @Override
    public void onNetStart() {

    }

    @Override
    public void onNetFinish() {

    }
}
